//
//  AddZhangDanTableViewController.m
//  ErJie
//
//  Created by yaorenjin on 2017/1/26.
//  Copyright © 2017年 yaorenjin. All rights reserved.
//

#import "AddZhangDanTableViewController.h"
#import "ZhangDanAddShangPinTableViewCell.h"
#import "ShangPinFenLeiTableViewController.h"
#import "ZhangDanEntity+CoreDataClass.h"
#import "CoreDataManager.h"
#import "ZhangDanAddShangPinButtonTableViewCell.h"  
#import "KeHuTableViewController.h"
#import "KeHuEntity+CoreDataClass.h"
#import "ZhangDanAddShowInfoTableViewCell.h"
#import "ShangPinModel.h"
#import "ZhangDanPayTypeTableViewCell.h"    

@interface AddZhangDanTableViewController () <UIAlertViewDelegate,UIActionSheetDelegate>
@property(nonatomic,strong)NSMutableArray* dataArry;
@property(nonatomic,strong)ZhangDanModel* zdEntity;
@property(nonatomic,strong)ShangPinModel* currentSPEntity;
@property(nonatomic,strong)KeHuModel* currentKeHuEntity;

@end

@implementation AddZhangDanTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.zdEntity = [[CoreDataManager shareManager] createZhangDanModel];
    
    self.dataArry = [[NSMutableArray alloc] init];

}
- (IBAction)finish:(id)sender {
    
    [self.view endEditing:YES];
    
    if (self.currentKeHuEntity.name == nil || [self.currentKeHuEntity.name isEqualToString:@""]) {
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请选择客户" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        
        return;
    }
    
    if (self.dataArry.count == 0) {
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请添加商品" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        
        return;
    }
    

    NSInteger zid = [[[CoreDataManager shareManager] getZid] integerValue];
    
    NSInteger zdsprId = [[[CoreDataManager shareManager] getZdsprId] integerValue];
    
    NSMutableArray* zdsprIdArry = [[NSMutableArray alloc] init];
    
    for (ShangPinModel* model in self.dataArry) {
        
        [zdsprIdArry addObject:[NSString stringWithFormat:@"%ld",zdsprId]];
        ++zdsprId;
        [[CoreDataManager shareManager] setZdsprId:zdsprId];
    }
    
    self.zdEntity.zdsprIds = [zdsprIdArry componentsJoinedByString:@","];
    self.zdEntity.kId = [NSNumber numberWithInteger:self.currentKeHuEntity.kId];
    self.zdEntity.kehuName = self.currentKeHuEntity.name;
    self.zdEntity.kehuPhone = self.currentKeHuEntity.phone;
    self.zdEntity.zId = zid;
    
    [[CoreDataManager shareManager] insertZhangDan:[[CoreDataManager shareManager] toZhangDanEntity:self.zdEntity] isHaveIds:YES];

    NSInteger i = 0;
    for (ShangPinModel* model in self.dataArry) {
        
        ZhangDanShangPinRelationEntity* zdsprEntity = [[CoreDataManager shareManager] createZhangDanShangPinRelationEntity];
        zdsprEntity.shuliang = [model.buyCount integerValue];
        zdsprEntity.spId = model.sId;
        zdsprEntity.zdId = zid;
        zdsprEntity.fId = model.fId;
        zdsprEntity.zdsprId = [[zdsprIdArry objectAtIndex:i] integerValue];
        ++i;
        
        [[CoreDataManager shareManager] insertZhangDanShangPinRelation:zdsprEntity isHaveIds:YES];
        
        //分类库存减去多少
        [[CoreDataManager shareManager] updateShangPinFenLeiId:[model.fId stringValue] kunCunCount:-([model.buyCount integerValue])];
        //商品库存减去多少
        [[CoreDataManager shareManager] updateShangPinId:[NSString stringWithFormat:@"%lld",model.sId] kunCunCount:-([model.buyCount integerValue])];

    }
    
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0) {
        
        return self.dataArry.count + 1;
    }
    
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == self.dataArry.count) {
            
            cell = [tableView dequeueReusableCellWithIdentifier:@"ZhangDanAddShangPinButtonTableViewCell"];

            ZhangDanAddShangPinButtonTableViewCell* spCell = (ZhangDanAddShangPinButtonTableViewCell*)cell;
            
            __weak typeof(self) weakSelf = self;
            
            spCell.btnClickBlock = ^()
            {
                ShangPinFenLeiTableViewController *viewController = [[UIStoryboard storyboardWithName:@"TabBarController" bundle:nil] instantiateViewControllerWithIdentifier:@"ShangPinFenLeiTableViewController"];
                viewController.title = @"选择商品分类";
                viewController.selectShangPinEntityBlock = ^(ShangPinEntity* spEntity)
                {
                    ShangPinModel* entity = [[CoreDataManager shareManager] toShangPinModel:spEntity];
                    weakSelf.currentSPEntity = entity;
                    
                    [weakSelf.dataArry addObject:weakSelf.currentSPEntity];
                    [tableView reloadData];
                    
                    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入数量" delegate:weakSelf cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
                    UITextField *textField = [alertView textFieldAtIndex:0];//获得输入框
                    textField.keyboardType = UIKeyboardTypeNumberPad;
                    [alertView show];
                    
                    [weakSelf.navigationController popToViewController:weakSelf animated:YES];

                };
                
                [weakSelf.navigationController pushViewController:viewController animated:YES];
            };
            
        }
        else
        {
            cell = [tableView dequeueReusableCellWithIdentifier:@"ZhangDanAddShangPinTableViewCell"];
            
            [cell performSelector:@selector(reloadData:) withObject:[self.dataArry objectAtIndex:indexPath.row]];
            
        }

        return cell;
        
    }
    else if (indexPath.section == 1)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:@"ZhangDanAddKeHuTableViewCell"];
        
        [cell performSelector:@selector(reloadData:) withObject:self.currentKeHuEntity];
        
    }
    else if (indexPath.section == 2)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:@"ZhangDanPayTypeTableViewCell"];
        ZhangDanPayTypeTableViewCell* typeCell = cell;
        
        //微转
        if ([self.zdEntity.payType integerValue] == 0) {
            
            typeCell.nameLabel.text = @"微转";

        }
        //打款
        else if ([self.zdEntity.payType integerValue] == 1)
        {
            typeCell.nameLabel.text = @"打款";

        }
        //现金
        else if ([self.zdEntity.payType integerValue] == 2)
        {
            typeCell.nameLabel.text = @"现金";

        }
        //欠款
        else if ([self.zdEntity.payType integerValue] == 3)
        {
            typeCell.nameLabel.text = @"欠款";

        }
        
    }
    else if (indexPath.section == 3)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:@"ZhangDanAddShowInfoTableViewCell"];
        
        ZhangDanAddShowInfoTableViewCell* showInfoCell = (ZhangDanAddShowInfoTableViewCell*)cell;
        
        CGFloat chenBtnFloat = 0.f;
        CGFloat zongJiaFloat = 0.f;
        
        for (ShangPinEntity* spEntity in self.dataArry) {
            
            chenBtnFloat += spEntity.chenben*[spEntity.buyCount integerValue];
            zongJiaFloat += [spEntity.danjia integerValue]*[spEntity.buyCount integerValue];
        }
        
        showInfoCell.chenBen.text = [NSString stringWithFormat:@"%0.2lf",chenBtnFloat];
        showInfoCell.lirunLabel.text = [NSString stringWithFormat:@"%0.2lf",zongJiaFloat-chenBtnFloat];
        showInfoCell.zongJiaTextField.text = [NSString stringWithFormat:@"%0.2lf",zongJiaFloat];
        self.zdEntity.zongjia = showInfoCell.zongJiaTextField.text;
        self.zdEntity.lirun = [NSString stringWithFormat:@"%0.2lf",[showInfoCell.zongJiaTextField.text floatValue]-chenBtnFloat];
        self.zdEntity.chenben = showInfoCell.chenBen.text;
        
        __weak ZhangDanAddShowInfoTableViewCell* weakCell = showInfoCell;
        
        showInfoCell.zongJiaTextFieldChange = ^(NSString* text)
        {
            weakCell.lirunLabel.text = [NSString stringWithFormat:@"%0.2lf",[text floatValue]-chenBtnFloat];

            self.zdEntity.zongjia = text;
            self.zdEntity.lirun = weakCell.lirunLabel.text;

        };
    }
   
    
    return cell;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex NS_DEPRECATED_IOS(2_0, 9_0);
{
    UITextField *textField = [alertView textFieldAtIndex:0];//获得输入框
    self.currentSPEntity.buyCount = @([textField.text integerValue]);//获得值
    [self.tableView reloadData];

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        if (indexPath.row == self.dataArry.count) {
            
            return 44;
        }
        else
        {
            return 44;
        }
    }
    else if (indexPath.section == 1)
    {
        return 44.f;
    }
    else if (indexPath.section == 2)
    {
        return 44.f;
    }
    else if (indexPath.section == 3)
    {
        return 90;
    }
    
    return 44.f;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1) {
        
        KeHuTableViewController *viewController = [[UIStoryboard storyboardWithName:@"TabBarController" bundle:nil] instantiateViewControllerWithIdentifier:@"KeHuTableViewController"];
        viewController.title = @"选择客户";
        viewController.selectKeHuEntity = ^(KeHuEntity* khEntity)
        {
            self.currentKeHuEntity = khEntity;
            [self.tableView reloadData];
        };
        
        [self.navigationController pushViewController:viewController animated:YES];

    }
    else if (indexPath.section == 2)
    {
        UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"付款方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"微转" otherButtonTitles:@"打款",@"现金",@"欠款", nil];
        [actionSheet showInView:self.view];
    }

}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex NS_DEPRECATED_IOS(2_0, 8_3) __TVOS_PROHIBITED
{
    self.zdEntity.payType = [NSNumber numberWithInt:buttonIndex];
    [self.tableView reloadData];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
